package com.example.mqttledmenu;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    ViewPager2 viewPager;
    private LinearLayout tab_home, tab_focus, tab_subscribe;
    private ImageView iv_home, iv_focus, iv_subscribe, iv_current;
    //初始化MQTT协议相关变量
    private static MqttAndroidClient mqttAndroidClient;
    String serverUrl = "tcp://test.ranye-iot.net:1883";//使用开源的服务器
    String clientId = "2f339b3eccd94c9da6726fa9a9eee9f3";//客户端的ID
    Boolean isConnect = false;
    private static final int REQUEST_CODE = 1;
    ArrayList<String> subscribeList = new ArrayList<>();
    private NotificationManager notificationManager;

    private void checkPermission() {
        try {
            String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            int permission = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_CODE);
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                Log.d("nightowl", "onRequestPermissionsResult: " + "拒绝文件权限！");
            } else {
                Log.d("nightowl", "onRequestPermissionsResult: " + "成功获取文件权限！");
            }
        }
    }

    public void getSubscribeList() {
        subscribeList = new ArrayList<>();//清空数据
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
        UploadService uploadService = retrofit.create(UploadService.class);
        Call<ResponseBody> call = uploadService.getPlate(Config.getInstance().getUserId());//与后端约定，不传入id直接获取全部
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String result = null;
                try {
                    result = response.body().string();
                    JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                    if (!returnData.get("code").toString().equals("200")) {
                        Toast.makeText(MainActivity.this, "服务端错误~", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    try {
                        JSONArray myjsonArray = new JSONArray(returnData.get("data").toString());
                        for (int i = 0; i < myjsonArray.length(); i++) {
                            JSONObject jsonObject = myjsonArray.getJSONObject(i);
                            if (jsonObject.get("isSubscribe").toString().equals("1")) {
                                subscribeList.add(jsonObject.get("tag").toString());
                            }
                        }
                    } catch (JSONException e) {
                        Log.d("nightowl", "onResponse: yichang");
                        e.printStackTrace();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission();
        initPager();
        initTabView();
        initTabbarListener();
        getSubscribeList();
        initMQTTService();
    }

    public void initMQTTService() {
        clientId = clientId + System.currentTimeMillis(); // 获取系统运行时间,保证ID的唯一性
        mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), serverUrl, clientId);
        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            public void connectComplete(boolean reconnect, String serverUrl) {
                if (!isConnect && reconnect) {
                    isConnect = true;
                    subscribeTopic();//订阅主题
                }
            }

            @Override
            public void connectionLost(Throwable cause) {
                Toast.makeText(MainActivity.this, "MQTT服务重连失败！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                noticeInfo(topic, message.toString());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                Toast.makeText(MainActivity.this, "  消息发送完成！", Toast.LENGTH_SHORT).show();
            }
        });
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();//定义一个mqttConnectOptions
        mqttConnectOptions.setAutomaticReconnect(true);//自动重连
        mqttConnectOptions.setCleanSession(false);//不清除会话
        try {
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    //  Toast.makeText(MainActivity.this, "MQTT服务器连接成功！", Toast.LENGTH_SHORT).show();
                    isConnect = true;
                    subscribeTopic();//订阅主题
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                   // Toast.makeText(MainActivity.this, "MQTT服务器首次连接失败~", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MqttException ex) {
            ex.printStackTrace();
        }
    }

    public void initTabbarListener() {
        final SoftKeyboardStateHelper softKeyboardStateHelper = new SoftKeyboardStateHelper(findViewById(R.id.activity_main));
        softKeyboardStateHelper.addSoftKeyboardStateListener(new SoftKeyboardStateHelper.SoftKeyboardStateListener() {
            @Override
            public void onSoftKeyboardOpened(int keyboardHeightInPx) {
                //键盘打开
                //Log.d("nightowl", "键盘打开");
                findViewById(R.id.table_bar).setVisibility(View.INVISIBLE);
            }

            @Override
            public void onSoftKeyboardClosed() {
                //键盘关闭
                // Log.d("nightowl", "键盘关闭");
                findViewById(R.id.table_bar).setVisibility(View.VISIBLE);
            }
        });
    }

    public void initTabView() {
        tab_home = findViewById(R.id.tab_home);
        tab_focus = findViewById(R.id.tab_focus);
        tab_subscribe = findViewById(R.id.tab_subscribe);

        tab_home.setOnClickListener(this);
        tab_focus.setOnClickListener(this);
        tab_subscribe.setOnClickListener(this);

        iv_home = findViewById(R.id.iv_home);
        iv_focus = findViewById(R.id.iv_focus);
        iv_subscribe = findViewById(R.id.iv_subscribe);

        iv_home.setOnClickListener(this);
        iv_focus.setOnClickListener(this);
        iv_subscribe.setOnClickListener(this);

        iv_home.setSelected(true);
        iv_current = iv_home;
    }

    private void changeTab(int position) {
        iv_current.setSelected(false);
        switch (position) {
            case 0:
                iv_home.setSelected(true);
                iv_current = iv_home;
                break;
            case 1:
                iv_focus.setSelected(true);
                iv_current = iv_focus;
                break;
            case 2:
                iv_subscribe.setSelected(true);
                iv_current = iv_subscribe;
                break;
        }
    }

    public void initPager() {
        viewPager = findViewById(R.id.viewPager);
        Toast.makeText(this, "欢迎回来!", Toast.LENGTH_SHORT).show();
        ArrayList<Fragment> fragments = new ArrayList<>();
        //添加Fragment页面
        fragments.add(new FragmentHome());
        fragments.add(new FragmentFocus());
        fragments.add(new FragmentSubscribe());
        FragmentPagerAdapter PagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager(), getLifecycle(), fragments);
        viewPager.setAdapter(PagerAdapter);
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                changeTab(position);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tab_home:
                viewPager.setCurrentItem(0);
                break;
            case R.id.tab_focus:
                viewPager.setCurrentItem(1);
                break;
            case R.id.tab_subscribe:
                viewPager.setCurrentItem(2);
                break;
        }
    }

    public void subscribeTopic() {
        int len = subscribeList.size();
        for (int i = 0; i < len; i++) {

            try {
                int finalI = i;
                mqttAndroidClient.subscribe(subscribeList.get(i), 0, null, new IMqttActionListener() {
                    //订阅成功的时候，就会调用
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {
                        if (len - 1 == finalI) {
                            Log.d("nightowl", "订阅主题成功！");
                        } else {
                            Log.d("nightowl", "订阅主题中！" + subscribeList.get(finalI));
                        }
                    }

                    //订阅失败的时候，就会调用
                    @Override
                    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                        Log.d("nightowl", "订阅主题失败~");
                    }
                });
            } catch (MqttException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void noticeInfo(String topic, String msg) {
        JsonObject newsInfo = new JsonParser().parse(msg).getAsJsonObject();
        String notice_title = newsInfo.get("title").toString().replace("\"", "");
        String news_id = newsInfo.get("news_id").toString();
        String department_name = newsInfo.get("department_name").toString().replace("\"", "");
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel manager = new NotificationChannel("campus_notice", "测试通知", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(manager);
        }
        //点击跳转到对应的app
        Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
        int notifyId = (int) System.currentTimeMillis();
        Bundle bundle = new Bundle();
        bundle.putString("news_id", news_id);
        bundle.putBoolean("need_read", true);
        intent.putExtras(bundle);
        PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(MainActivity.this, "campus_notice")
                .setContentText(department_name + "~")
                .setContentText(notice_title)
                .setSmallIcon(R.drawable.campus_notice)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .build();
        notificationManager.notify(notifyId, notification);
    }
}
